package com.gdk.ksoft.ui.logins;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.SaleManTable;
import com.gdk.ksoft.assembly.utils.system.ConfigUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 找回密码页面
 */
public class FindPwdActivity extends Activity {

    @ViewInject(R.id.pfindpwd_etPassword)private EditText etPassword;//密码输入框
    @ViewInject(R.id.pfindpwd_etAgainPassword)private EditText etAgainPassword;//重复密码输入框
    @ViewInject(R.id.pfindPwd_txtTip)private TextView txtTip;//提示文字

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_pwd);
        ViewUtils.inject(this);
    }

    @OnClick(value={R.id.pfindpwd_txtSubmit,R.id.pfindpwd_imgBack})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pfindpwd_imgBack://返回
                this.finish();
                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                break;
            case R.id.pfindpwd_txtSubmit://提交
                if(!checkPassword()) return;//检测密码输入
                changePassword(this,etAgainPassword.getText().toString());//修改密码
                break;
        }
    }

    /**
     * 检测密码输入
     * @return
     */
    public boolean checkPassword(){
        String password = etPassword.getText().toString();
        if(TextUtils.isEmpty(password)){
            etPassword.setError("请输入新密码!");
            return false;
        }
        String againPassword = etAgainPassword.getText().toString();
        if(TextUtils.isEmpty(againPassword)){
            etPassword.setError("请重复新密码!");
            return false;
        }
        if(!password.equals(againPassword)){
            etPassword.setError("两次输入的密码不正确!");
            return false;
        }
        return true;
    }

    /**
     * 修改密码
     * @param context
     */
    public void changePassword(final Context context,final String password){
        if(NetworkUtils.isNetAvailable(context)){
            final ProgressDialog dialog = ProgressDialog.show(context, "","正在提交数据...");
            String methodName = "Cx_UpdateSsmm";
            String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"ssmm\":\""+password+"\"}}";
            System.out.println("-----> 正在修改业务员登录密码数据：" + messageBody);
            RequestParams params = new RequestParams("UTF-8");
            params.addBodyParameter("Method", methodName);
            params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
            params.addBodyParameter("MessageBody", messageBody);
            new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT).configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                    .send(HttpRequest.HttpMethod.POST, SystemData.BASE_URL,params,new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> str) {
                    System.out.println("------>修改业务员登录密码结果："+str.result);
                    hideProgressDialog();//隐藏进度对话框
                    BaseResultModel resultModel = new Gson().fromJson(str.result,BaseResultModel.class);
                    if(resultModel.Result.equals("0000")){//修改成功
                        try {
                            ConfigUtils.getInstance(context).getEditor().putString(LoginActivity.PASSWORD_FIELD, "").commit();
                            DbUtils dbUtils = SQLiteUtils.getInstance(context).getDbUtils();
                            final SaleManTable saleManTable = dbUtils.findFirst(SaleManTable.class);
                            saleManTable.ssmm = password;
                            dbUtils.update(saleManTable, "ssmm");
                            Toast.makeText(context, "修改密码成功!", Toast.LENGTH_SHORT).show();
                            //关闭当前页面
                            Activity activity = ((Activity)context);
                            activity.finish();
                            overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                        }catch(Exception e){
                            e.printStackTrace();
                            Toast.makeText(context,"修改密码失败!原因："+e.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(context,"修改密码失败!原因："+resultModel.Message,Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    hideProgressDialog();//隐藏进度对话框
                    Toast.makeText(context,"网络访问失败!",Toast.LENGTH_SHORT).show();
                }

                /**
                 * 隐藏进度对话框
                 */
                public void hideProgressDialog(){
                    if(dialog!=null && dialog.isShowing())
                        dialog.dismiss();
                }
            });
        }else{
            Toast.makeText(context,"请检查你的网络连接是否正常!",Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
            this.finish();
            overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
